package com.znyj.servlet.secondaryController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.znyj.servlet.entity.FactoryEntity;
import com.znyj.servlet.entity.UserEntity;
import com.znyj.servlet.service.FactoryService;
import com.znyj.servlet.service.UserService;
import com.znyj.servlet.thrift.ThriftClient;
import com.znyj.servlet.utilsTool.CommonTool;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by gaoliwei02 on 17/7/25.
 */
@Controller
@RequestMapping(value = "/factory")
public class FactoryController {

    @Resource
    private FactoryService factoryService;
    @Resource
    private UserService userService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    protected @ResponseBody String factoryLogin(@RequestBody String receiveData) throws ParseException, IOException {
        JSONObject getJson = JSON.parseObject(receiveData);
        String username = getJson.getString("username");
        String password = getJson.getString("password");

        UserEntity userEntity = userService.findByUsername(username);
        if (userEntity == null) {
            //没有注册
            return "nouser";
        } else {
            if (userEntity.getPassWord().equals(password)) {
                //密码对上了，登录成功
                JSONObject putJson = new JSONObject();
                assembleArray(putJson, "deviceType", "1.CDB,2.POS");
                assembleArray(putJson, "commType", "1.GPRS,2.BT,3.WIFI");
                assembleArray(putJson, "country", "1.china,2.Indonesia");
                assembleArray(putJson, "IOTID", "1.YX510");
                assembleArray(putJson, "MCUID", "1.MCS52");
                assembleArray(putJson, "QAMID", "1.TESTV1.1");
                assembleArray(putJson, "PCBID", "1.CDB2017-07-20");
                assembleArray(putJson, "MCUSV", "1.V1.1");
                assembleArray(putJson, "factory", "1.shenzhen,2.beijing");
                return putJson.toString();
            } else {
                //密码错误
                return "error";
            }
        }
    }

    @RequestMapping(value = "/finish", method = RequestMethod.POST)
    protected @ResponseBody String factoryFinish(@RequestBody String receiveData) throws ParseException, IOException {
        JSONObject getJson = JSON.parseObject(receiveData);
        String deviceId = getJson.getString("deviceId");
        String userId = getJson.getString("userId");
        String res = null;

        String isOnline = ThriftClient.getRealTimeDeviceInfo(deviceId);
        long timeStamp = new Timestamp(System.currentTimeMillis()).getTime();
        if (isOnline.equals("online")) {
            JSONObject putJson = ThriftClient.taskSendThriftApi(userId, deviceId, timeStamp, 0, "opencdb", "");
            factoryService.updateReborn("ok", deviceId);
            res = putJson.getString("status");
        } else if (isOnline.equals("offline")) {
            factoryService.updateReborn("fail", deviceId);
            res = "in queue";
        }else{
            res = "error";
        }
        return res;
    }

    @RequestMapping(value = "/info", method = RequestMethod.POST)
    protected @ResponseBody String factoryInfo(@RequestBody String receiveData) throws ParseException, IOException {
        JSONObject getJson = JSON.parseObject(receiveData);
        FactoryEntity factoryEntity = new FactoryEntity();

        factoryEntity.setUserId(getJson.getString("userId"));
        factoryEntity.setReborn("");
        factoryEntity.setCommType(getJson.getString("commType"));
        factoryEntity.setDeviceType(getJson.getString("deviceType"));
        factoryEntity.setCountry(getJson.getString("country"));
        factoryEntity.setIotId(getJson.getString("IOTID"));
        factoryEntity.setMcuId(getJson.getString("MCUID"));
        factoryEntity.setQamId(getJson.getString("QAMID"));
        factoryEntity.setPcbId(getJson.getString("PCBID"));
        factoryEntity.setMcuSv(getJson.getString("MCUSV"));
        factoryEntity.setFactory(getJson.getString("factory"));
        factoryEntity.setImei(getJson.getString("IMEI"));
        factoryEntity.setCreatedTime(new Timestamp(System.currentTimeMillis()));


        int count = factoryService.countByImei(factoryEntity.getImei());
        if (count == 0) {
            String devId = CommonTool.createDeviceId(factoryEntity);
            factoryEntity.setDeviceId(devId);
            factoryService.insertFactory(factoryEntity);
        } else if (count == 1) {
            FactoryEntity repeatedEntity = factoryService.findByImei(factoryEntity.getImei());
            factoryEntity.setDeviceId(repeatedEntity.getDeviceId());
            factoryService.updateFactory(factoryEntity);
        } else {
            factoryService.deleteByImei(factoryEntity.getImei());
            String devId = CommonTool.createDeviceId(factoryEntity);
            factoryEntity.setDeviceId(devId);
            factoryService.insertFactory(factoryEntity);
        }

        JSONObject putJson = new JSONObject();

        putJson.put("DEVID", String.valueOf(factoryEntity.getDeviceId()));
        return putJson.toString();
    }

    void assembleArray(JSONObject putJson, String name, String list) {
        String[] arr = list.split(",");
        List<String> stringlist = new ArrayList<String>(Arrays.asList(arr));
        JSONArray jsonArray = new JSONArray();
        for (String next : stringlist) {
            jsonArray.add(next);
        }
        putJson.put(name, jsonArray);
    }
}






